package common

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"strconv"
	"time"
	"unsafe"
)

func IsContain(items []string, item string) bool {
	for _, eachItem := range items {
		if eachItem == item {
			return true
		}
	}
	return false
}

func RandomString(n int) string {
	//字符串切片
	var letters = []byte("qwertyuioplkjhgfdsazxcvbnm")

	//定义一个长度为n的切片
	result := make([]byte, n)

	for i := range result {
		//rand.Intn:随机取0-参数长度的值
		result[i] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}

func HttpGet(url string) string {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	resp, err := client.Get(url)
	if err != nil {
		return err.Error()
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return err.Error()
	}
	return string(body)
}

func HttpPost(url string, code string) string {
	query := make(map[string]string)
	query["code"] = code
	bytesData, err := json.Marshal(query)
	if err != nil {
		return err.Error()
	}
	reader := bytes.NewReader(bytesData)
	request, err := http.NewRequest("POST", url, reader)
	//defer request.Body.Close() //程序在使用完回复后必须关闭回复的主体
	if err != nil {
		return err.Error()
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	//必须设定该参数,POST参数才能正常提交，意思是以json串提交数据

	client := http.Client{}
	resp, err := client.Do(request) //Do 方法发送请求，返回 HTTP 回复
	if err != nil {
		return err.Error()
	}

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err.Error()
	}

	//byte数组直接转成string，优化内存
	str := (*string)(unsafe.Pointer(&respBytes))

	return string(*str)
}

func RandomCode() string {
	rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
	result := fmt.Sprintf("%06v", rnd.Int31n(1000000))
	return string(result)
}

// 判断元素是否在slice中
func InSlice(v string, s []string) bool {
	for _, vv := range s {
		if vv == v {
			return true
		}
	}
	return false
}

func ArrayToString(arr []string) string {
	var result string
	for _, i := range arr { //遍历数组中所有元素追加成string
		result += "'" + i + "'" + ","
	}
	return result
}

func ArrayToStringInt(arr []string) string {
	var result string
	for _, i := range arr { //遍历数组中所有元素追加成string
		result += i + ","
	}
	return result
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func ExcelDateToDate(excelDate string) time.Time {
	excelTime := time.Date(1899, time.December, 30, 0, 0, 0, 0, time.UTC)
	var days, _ = strconv.Atoi(excelDate)
	return excelTime.Add(time.Second * time.Duration(days*86400))
}
